import store from '../../store'
export default {
  apiWebHost: 'https://smygc.zhunzhe.cn/api-prod',
  adminToken: 'token',
  adminAdress: '',
  token: '',
  status: false,
  APIURL: function(action) {
    return this.apiWebHost + action
  },
  ImgFile: function(id) {
    return this.ImgUrl + id
  },
  HImgFile: function(id, w, h) {
    if (id) {
      var url = this.HImgUrl + id
      if (w) {
        url += '?resize=w_' + w
      }
      if (h) {
        url += ',h_' + h
      }
      return url
    }
  },
  // 记录缓存
  setCookie: function(name, value) { //设置cookie，默认保存7天
    uni.setStorage({
      key: name,
      data: value,
      success: function() {
        console.log('success')
      }
    })
  },
  // 获取缓存
  getStorage: function(key, callback) {
    return new Promise(resolve => {
      uni.getStorage({
        key: key,
        success: function(res) {
          resolve(res.data)
        },
        fail: function(res) {
          resolve(res.data)
        },
        complete: function(res) {
          resolve(res.data)
        },
      })
    })
  },
  // 上传
  upload(tempFilePaths) {
    return new Promise(resolve => {
      let imgList = []
      tempFilePaths.forEach((item, index) => {
        uni.uploadFile({
          url: 'https://car.zhenpinvip.com/api-fl/v2/zz/fileupload', //仅为示例，非真实的接口地址
          filePath: item,
          name: 'file',
          success: uploadFileRes => {
            let res = JSON.parse(uploadFileRes.data)
            if (!res.error) {
              imgList.push(res.result)
              console.log(imgList)
              if (index == tempFilePaths.length - 1) {
                resolve(imgList)
              }
            }
          }
        })
      })


    })
  },
  // 上传图片
  ChooseImage(num) {
    return new Promise(resolve => {
      uni.chooseImage({
        count: num, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], //从相册选择
        success: res => {
          const tempFilePaths = res.tempFilePaths
          let uploadimg = this.upload(tempFilePaths)

          uploadimg.then(result => {
            resolve(result)
          })
        }
      })
    })
  },
  //删除缓存
  remove: function(name) {
    return new Promise(resolve => {
      uni.removeStorage({
        key: name,
        success: function(res) {
          resolve(res)
        }
      })
    })
  },
  ajax: function(opt) {
    opt = opt || {}
    opt.url = this.APIURL(opt.url) || ''
    opt.data = opt.data || null
    opt.method = opt.method || 'GET'
    opt.header = opt.header || {
      'Authorization': this.token ? `Bearer ${this.token}` : '',
      'content-type': 'application/json',
      'Accept': 'application/json',
      'tenant': this.adminAdress ? this.adminAdress : ''
    }
    let _this = this
    opt.success = opt.success || function() {}
    opt.error = opt.success || function() {}
    uni.request({
      url: opt.url,
      data: opt.data,
      method: opt.method,
      header: opt.header,
      dataType: 'json',
      success: function(res) {
        if (res.data.code == 401) {
          store.state.token = '';
          store.state.hasLogin = false;
          _this.remove(_this.adminToken)
          uni.navigateTo({
            url: '/pages/public/login'
          })
          opt.success(res.data)
          return
        } else if (res.data.code !== 200) {
          opt.error(res.data)
          return
        } else {
          opt.success(res.data)
        }
      },
      fail: function(res) {},
      complete(res) {
        if (res.data && res.data.error) {
          uni.showToast({
            title: res.data.error,
            icon: 'none',
            duration: 1000
          })
        }
      }
    })
  },
  formatTime(seconds) {
    // 计算天数、小时数、分钟数和剩余秒数
    // const days = Math.floor(seconds / (24 * 60 * 60));
    const hours = Math.floor(seconds / (60 * 60))
    const minutes = Math.floor((seconds % (60 * 60)) / 60)
    const remainingSeconds = seconds % 60
    // 返回格式化的时间字符串
    return `${hours}小时${minutes}分`
  },
  dateCalculation: function(data) { //返回天、时、分
    var newTime = data.replace(/\-/g, '/')
    let nowdata = new Date().getTime()
    let enddata = new Date(newTime).getTime()
    let second = parseInt(enddata - nowdata)
    if (second > 0) {
      let data = {}
      let day = parseInt(second / (1000 * 60 * 60 * 24))
      let hour = parseInt((second % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      let minute = parseInt((second % (1000 * 60 * 60)) / (1000 * 60))
      let seconds = (second % (1000 * 60)) / 1000
      data.day = day
      data.hour = hour
      data.minute = minute
      data.seconds = seconds
      return data
    }
  },
  TdateCalculation: function(data) { //返回天、时、分
    var newTime = data.replace(/\-/g, '/')
    let nowdata = new Date().getTime()
    let enddata = new Date(newTime).getTime()
    let second = parseInt(enddata - nowdata)
    return second
  },
  getThisWeekDays: function() {
    const today = new Date()
    const daysOfWeek = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    const weekDaysnumber = ['07', '01', '02', '03', '04', '05', '06']
    const weekDays = []
    // 获取本周的开始日期（周日）
    let startOfWeek = new Date(today)
    let todyDate = this.getNowDate()
    startOfWeek.setDate(today.getDate() - today.getDay() + 1)
    // 获取本周的结束日期（周六）
    let endOfWeek = new Date(today)
    endOfWeek.setDate(today.getDate() - today.getDay() + 7)
    // 循环本周每一天，生成对象并添加到数组中
    for (let i = 0; i < 7; i++) {
      const day = new Date(startOfWeek)
      day.setDate(startOfWeek.getDate() + i)
      const dayOfWeek = daysOfWeek[day.getDay()]
      const formattedDate = day.toISOString().split('T')[0]
      weekDays.push({ name: dayOfWeek, date: formattedDate, istoday: todyDate == formattedDate ? true : false, num: weekDaysnumber[day.getDay()] })
    }
    // 返回包含本周每天的对象数组
    return weekDays
  },
  //格式化日期，format:格式，默认yyyy-MM-dd,date时间，默认当前时间
  getNowDate: function(format, date) {
    if (!format) {
      format = 'yyyy-MM-dd'
    }

    var now = new Date()
    if (date) {
      // var newTime = date.replace(/\-/g, "/");
      now = new Date(date)

    }
    var year = now.getFullYear() //年
    var month = now.getMonth() + 1 //月
    var day = now.getDate() //日
    var hh = now.getHours()
    var mm = now.getMinutes()
    var ss = now.getSeconds()

    var clock = year + '/'
    switch (format) {
      case 'yyyy-MM-dd': {
        if (month < 10)
          clock += '0'
        clock += month + '-'
        if (day < 10) {
          clock += '0'
        }
        clock += day
      }
      break
      case 'yyyy-MM': {
        if (month < 10)
          clock += '0'
        clock += month
      }
      break
      case 'yyyy-MM-dd HH:mm': {
        if (month < 10)
          clock += '0'
        clock += month + '-'
        if (day < 10) {
          clock += '0'
        }
        clock += day + ' '

        if (hh < 10)
          clock += '0'
        clock += hh + ':'
        if (mm < 10)
          clock += '0'
        clock += mm + ':'
        if (ss < 10)
          clock += '0'
        clock += ss
        clock = clock.substring(0, 16)
      }
      break
      case 'yyyy-MM-dd HH': {
        if (month < 10)
          clock += '0'
        clock += month + '-'
        if (day < 10) {
          clock += '0'
        }
        clock += day + ' '
        if (hh < 10)
          clock += '0'
        clock += hh
      }
      break
      case 'yyyy-MM-ddTHH:mm': {
        if (month < 10)
          clock += '0'
        clock += month + '-'
        if (day < 10) {
          clock += '0'
        }
        clock += day + 'T'

        if (hh < 10)
          clock += '0'
        clock += hh + ':'
        if (mm < 10)
          clock += '0'
        clock += mm + ':'
        if (ss < 10)
          clock += '0'
        clock += ss
        clock = clock.substring(0, 16)
      }
      break
      case 'yyyy-MM-dd HH:mm:ss': {
        if (month < 10)
          clock += '0'
        clock += month + '/'
        if (day < 10) {
          clock += '0'
        }
        clock += day + ' '

        if (hh < 10)
          clock += '0'
        clock += hh + ':'
        if (mm < 10)
          clock += '0'
        clock += mm + ':'
        if (ss < 10)
          clock += '0'
        clock += ss
      }
      break
      case 'yyyy/MM/dd HH:mm:ss': {
        if (month < 10)
          clock += '0'
        clock += month + '/'
        if (day < 10) {
          clock += '0'
        }
        clock += day + ' '

        if (hh < 10)
          clock += '0'
        clock += hh + ':'
        if (mm < 10)
          clock += '0'
        clock += mm + ':'
        if (ss < 10)
          clock += '0'
        clock += ss
      }
      break
      case 'yyyyMMddHHmmss': {
        clock = year
        if (month < 10)
          clock += '0'
        clock += month
        if (day < 10) {
          clock += '0'
        }
        clock += day

        if (hh < 10)
          clock += '0'
        clock += hh
        if (mm < 10)
          clock += '0'
        clock += mm
        if (ss < 10)
          clock += '0'
        clock += ss
      }
      break
      case 'MMddHHmm': {
        var nowdata = new Date()
        var nowYear = nowdata.getFullYear()
        var nowMonth = nowdata.getMonth() + 1
        var nowDay = nowdata.getDate()
        var nowdatastr = nowYear + nowMonth + nowDay
        var datastr = year + month + day
        if (nowdatastr == datastr) {
          clock += hh + ':'
          clock += mm
        } else {
          clock += month + '-'
          clock += day + ' '
          clock += hh + ':'
          clock += mm
        }
      }
      break
    }

    return clock

  },

}